import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '../store/index';
// start auto load routers to the index.ts
const autoLoadRoutes: Array<RouteRecordRaw> = [];
// match in the router catalogue "xxx.router.ts"
const reqRouter = require.context('./', true, /\.router\.ts$/);
// loop add router on the variable autoLoadRoutes
reqRouter.keys().forEach((name) => {
  autoLoadRoutes.push(...reqRouter(name).default);
});
// init routes to variable
const routes: Array<RouteRecordRaw> = [
  {
    path: '/Login',
    name: 'Login',
    component: () => import('../views/login/login.vue')
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('../views/basic/basic-index.vue'),
    children: [
      {
        path: '/Home',
        name: 'Home',
        component: () => import('../views/common/home.vue')
      },
      // add children's router on the routes variable
      ...autoLoadRoutes
    ]
  }
]
// create router
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// init "Navigation Guards" of vue router
router.beforeEach((to, from, next) => {
  if (to.name === 'Login') {
    next();
    return;
  }
  if (store.state.token) {
    next();
  } else {
    next({
      name: 'Login'
    });
  }
});

export default router
